<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="聚合聚合通常在mysql中是group by，例如统计sum等操作，MongoDB也为我们提供了聚合操作，但是实现却不一样。 group()这次需要的数据会比较多，这次直接用js来准数据。 1234for(var i = 1; i &amp;lt; 30; ++i ) &amp;#123;    var count = i % 5;    db.mygroup.insert(&amp;#123;name: &apos;name&apos;">
<meta name="keywords" content="Mongo">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB3-三种聚合操作详解">
<meta property="og:url" content="http://www.saily.top/2018/01/01/mongo3/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="聚合聚合通常在mysql中是group by，例如统计sum等操作，MongoDB也为我们提供了聚合操作，但是实现却不一样。 group()这次需要的数据会比较多，这次直接用js来准数据。 1234for(var i = 1; i &amp;lt; 30; ++i ) &amp;#123;    var count = i % 5;    db.mygroup.insert(&amp;#123;name: &apos;name&apos;">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.saily.top/img/mongo/mongo3-1.png">
<meta property="og:image" content="https://docs.mongodb.com/manual/_images/map-reduce.bakedsvg.svg">
<meta property="og:image" content="https://docs.mongodb.com/manual/_images/aggregation-pipeline.bakedsvg.svg">
<meta property="og:updated_time" content="2018-01-27T03:24:40.051Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB3-三种聚合操作详解">
<meta name="twitter:description" content="聚合聚合通常在mysql中是group by，例如统计sum等操作，MongoDB也为我们提供了聚合操作，但是实现却不一样。 group()这次需要的数据会比较多，这次直接用js来准数据。 1234for(var i = 1; i &amp;lt; 30; ++i ) &amp;#123;    var count = i % 5;    db.mygroup.insert(&amp;#123;name: &apos;name&apos;">
<meta name="twitter:image" content="http://www.saily.top/img/mongo/mongo3-1.png">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/01/01/mongo3/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>MongoDB3-三种聚合操作详解 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/01/01/mongo3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MongoDB3-三种聚合操作详解
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-01T10:56:37+08:00">1月 1 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Mongo/" itemprop="url" rel="index"><span itemprop="name">Mongo</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="聚合"><a href="#聚合" class="headerlink" title="聚合"></a>聚合</h1><p>聚合通常在mysql中是group by，例如统计sum等操作，MongoDB也为我们提供了聚合操作，但是实现却不一样。</p>
<h2 id="group"><a href="#group" class="headerlink" title="group()"></a>group()</h2><p>这次需要的数据会比较多，这次直接用js来准数据。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="number">30</span>; ++i ) &#123;</span><br><span class="line">    <span class="keyword">var</span> count = i % <span class="number">5</span>;</span><br><span class="line">    db.mygroup.insert(&#123;<span class="attr">name</span>: <span class="string">'name'</span> + i, <span class="attr">count</span> : count&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<p>mongo3.4开始，这个方法已经被官方弃用了，用<a href="#聚合框架（aggregation-framework）">db.collection.aggregate()</a>替代了，不过这里的例子仍然以db.collection.group()进行讲解。</p>
<h3 id="实例-计数"><a href="#实例-计数" class="headerlink" title="实例-计数"></a>实例-计数</h3><p>我们需要按照count字段进行分组然后统计每个分组的数量</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.mygroup.group(&#123;<span class="attr">key</span>: &#123;<span class="attr">count</span>:<span class="literal">true</span>&#125;, <span class="attr">initial</span>: &#123;<span class="attr">totalCount</span>:<span class="number">0</span>&#125;, <span class="attr">reduce</span>: <span class="function"><span class="keyword">function</span>(<span class="params">current, aggregator</span>)</span>&#123;</span><br><span class="line">...         aggregator.totalCount++;</span><br><span class="line">...     &#125;&#125;);</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">6</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">6</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">3</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">6</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">4</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">6</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">5</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p>参数解释：</p>
<ul>
<li>key： 需要分组的字段</li>
<li>initial：每一组初始化的值</li>
<li>reduce：计算</li>
<li>keyf：二次计算然后产生的key值</li>
<li>cond：查询条件</li>
<li>finalize：完成器，在返回之前对结果进行计算</li>
</ul>
<p>reduce的两个参数，就是分组后对数据的处理，current表示每次循环的当前对象，aggregator则每一组拥有一个共享对象，所以在这个例子里aggregator的totalCount每一组开始循环的时候都是0，最终统计出来每一组的总数。</p>
<p>关于这些的详细介绍，官网文档也给了非常好的介绍：<a href="https://docs.mongodb.com/manual/reference/method/db.collection.group/index.html" target="_blank" rel="noopener">https://docs.mongodb.com/manual/reference/method/db.collection.group/index.html</a></p>
<p><img src="/img/mongo/mongo3-1.png" alt=""></p>
<h3 id="实例-最大值"><a href="#实例-最大值" class="headerlink" title="实例-最大值"></a>实例-最大值</h3><p>重新准备数据：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">db.mygroup.drop()</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="number">30</span>; ++i ) &#123;</span><br><span class="line">    <span class="keyword">var</span> count = i % <span class="number">5</span>;</span><br><span class="line">    db.mygroup.insert(&#123;<span class="attr">name</span>: <span class="string">'name'</span> + i, <span class="attr">age</span>:i, <span class="attr">count</span> : count&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以count作为分组，取出每一组里age最大值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.mygroup.group(&#123;<span class="attr">key</span>: &#123;<span class="attr">count</span>:<span class="literal">true</span>&#125;, <span class="attr">initial</span>: &#123;<span class="attr">maxAge</span>:<span class="number">-1</span>&#125;, <span class="attr">reduce</span>: <span class="function"><span class="keyword">function</span>(<span class="params">current, aggregator</span>)</span>&#123;</span><br><span class="line">...         if(current.age &gt; aggregator.maxAge) &#123;</span><br><span class="line">...             aggregator.maxAge = current.age</span><br><span class="line">...         &#125;</span><br><span class="line">...     &#125;&#125;);</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"maxAge"</span> : <span class="number">26</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"maxAge"</span> : <span class="number">27</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">3</span>,</span><br><span class="line">		<span class="string">"maxAge"</span> : <span class="number">28</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">4</span>,</span><br><span class="line">		<span class="string">"maxAge"</span> : <span class="number">29</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">0</span>,</span><br><span class="line">		<span class="string">"maxAge"</span> : <span class="number">25</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h3 id="实例-找最小值"><a href="#实例-找最小值" class="headerlink" title="实例-找最小值"></a>实例-找最小值</h3><p>找出年龄最小值，这里优化一下效率</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.mygroup.group(&#123;<span class="attr">key</span>: &#123;<span class="attr">count</span>:<span class="literal">true</span>&#125;, <span class="attr">initial</span>: &#123;<span class="attr">minAge</span>:<span class="number">0</span>, <span class="attr">count</span>:<span class="number">0</span>&#125;, <span class="attr">reduce</span>: <span class="function"><span class="keyword">function</span>(<span class="params">current, aggregator</span>)</span>&#123;</span><br><span class="line">...         if(aggregator.count == <span class="number">0</span>) &#123;</span><br><span class="line">...             aggregator.minAge = current.age;</span><br><span class="line">...             aggregator.count++;</span><br><span class="line">...         &#125;<span class="keyword">else</span> <span class="keyword">if</span>(current.age &lt; aggregator.minAge) &#123;</span><br><span class="line">...             aggregator.minAge = current.age</span><br><span class="line">...             aggregator.count++;</span><br><span class="line">...         &#125;</span><br><span class="line">...     &#125;&#125;);</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">1</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">2</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">3</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">4</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">5</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h3 id="实例4-平均值"><a href="#实例4-平均值" class="headerlink" title="实例4-平均值"></a>实例4-平均值</h3><p>这个例子需要使用finalize完成器来做，先用reduce来完成计数和求和的操作，然后用finalize完成器来求平均值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.mygroup.group(&#123;<span class="attr">key</span>: &#123;<span class="attr">count</span>:<span class="literal">true</span>&#125;, <span class="attr">initial</span>: &#123;<span class="attr">minAge</span>:<span class="number">0</span>, <span class="attr">count</span>:<span class="number">0</span>, <span class="attr">totalAge</span>:<span class="number">0</span>,<span class="attr">totalCount</span>:<span class="number">0</span>&#125;, <span class="attr">reduce</span>: <span class="function"><span class="keyword">function</span>(<span class="params">current, aggregator</span>)</span>&#123;</span><br><span class="line">...         if(aggregator.count == <span class="number">0</span>) &#123;</span><br><span class="line">...             aggregator.minAge = current.age;</span><br><span class="line">...             aggregator.count++</span><br><span class="line">...         &#125;<span class="keyword">else</span> <span class="keyword">if</span>(current.age &lt; aggregator.minAge) &#123;</span><br><span class="line">...             aggregator.minAge = current.age</span><br><span class="line">...             aggregator.count++</span><br><span class="line">...         &#125;</span><br><span class="line">...         aggregator.totalCount++;</span><br><span class="line">...         aggregator.totalAge += current.age;</span><br><span class="line">...     &#125;, <span class="attr">finalize</span>: <span class="function"><span class="keyword">function</span>(<span class="params">aggregator</span>) </span>&#123;</span><br><span class="line">...         aggregator.avgAge = aggregator.totalAge / aggregator.totalCount;</span><br><span class="line">...     &#125;&#125;);</span><br><span class="line">[</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"totalAge"</span> : <span class="number">81</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">6</span>,</span><br><span class="line">		<span class="string">"avgAge"</span> : <span class="number">13.5</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">2</span>,</span><br><span class="line">		<span class="string">"totalAge"</span> : <span class="number">87</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">6</span>,</span><br><span class="line">		<span class="string">"avgAge"</span> : <span class="number">14.5</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">3</span>,</span><br><span class="line">		<span class="string">"totalAge"</span> : <span class="number">93</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">6</span>,</span><br><span class="line">		<span class="string">"avgAge"</span> : <span class="number">15.5</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">4</span>,</span><br><span class="line">		<span class="string">"totalAge"</span> : <span class="number">99</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">6</span>,</span><br><span class="line">		<span class="string">"avgAge"</span> : <span class="number">16.5</span></span><br><span class="line">	&#125;,</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="string">"count"</span> : <span class="number">1</span>,</span><br><span class="line">		<span class="string">"minAge"</span> : <span class="number">5</span>,</span><br><span class="line">		<span class="string">"totalAge"</span> : <span class="number">75</span>,</span><br><span class="line">		<span class="string">"totalCount"</span> : <span class="number">5</span>,</span><br><span class="line">		<span class="string">"avgAge"</span> : <span class="number">15</span></span><br><span class="line">	&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<h2 id="mapReduce"><a href="#mapReduce" class="headerlink" title="mapReduce"></a>mapReduce</h2><p>mapReduce主要分为两个阶段，mapReduce在mongodb中可以在分片的环境中运行，而group则不行。</p>
<ul>
<li>map阶段<br>  处理数据，例如分组，转换等</li>
<li>reduce阶段<br>  根据map的输出计算数据，得到想要的结果</li>
</ul>
<p><a href="https://docs.mongodb.com/manual/reference/command/mapReduce/index.html" target="_blank" rel="noopener">https://docs.mongodb.com/manual/reference/command/mapReduce/index.html</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">db.runCommand(</span><br><span class="line">               &#123;</span><br><span class="line">                 mapReduce: <span class="xml"><span class="tag">&lt;<span class="name">collection</span>&gt;</span>,</span></span><br><span class="line">                 map: &lt;function&gt;,</span><br><span class="line">                 reduce: &lt;function&gt;,</span><br><span class="line">                 finalize: &lt;function&gt;,</span><br><span class="line">                 out: &lt;output&gt;,</span><br><span class="line">                 query: &lt;document&gt;,</span><br><span class="line">                 sort: &lt;document&gt;,</span><br><span class="line">                 limit: &lt;number&gt;,</span><br><span class="line">                 scope: &lt;document&gt;,</span><br><span class="line">                 jsMode: &lt;boolean&gt;,</span><br><span class="line">                 verbose: &lt;boolean&gt;,</span><br><span class="line">                 bypassDocumentValidation: &lt;boolean&gt;,</span><br><span class="line">                 collation: &lt;document&gt;</span><br><span class="line">               &#125;</span><br><span class="line">             )</span><br></pre></td></tr></table></figure>
<p><img src="https://docs.mongodb.com/manual/_images/map-reduce.bakedsvg.svg" alt=""></p>
<blockquote>
<p>For those keys that have multiple values, MongoDB applies the reduce phase, which collects and condenses the aggregated data. </p>
</blockquote>
<p>map的结果只有一个值的话，是不会运行reduce的。</p>
<h3 id="实例1-求长度"><a href="#实例1-求长度" class="headerlink" title="实例1-求长度"></a>实例1-求长度</h3><p>数据准备：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="number">10</span>; ++i ) &#123;</span><br><span class="line">    <span class="keyword">var</span> count = i % <span class="number">3</span>;</span><br><span class="line">    db.student.insert(&#123;<span class="attr">name</span>: <span class="string">'name'</span> + i, <span class="attr">age</span>:i, <span class="attr">count</span> : count&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>现在用MapReduce来统计每一组数据长度。</p>
<p>map必须调用emit函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.getCollection(<span class="string">'student'</span>).mapReduce(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;emit(<span class="keyword">this</span>.count, <span class="number">1</span>)&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">key, values</span>)</span>&#123;<span class="keyword">return</span> values.length;&#125;, &#123;<span class="attr">out</span>:<span class="string">"length"</span>&#125;)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"result"</span> : <span class="string">"length"</span>,</span><br><span class="line">	<span class="string">"timeMillis"</span> : <span class="number">58</span>,</span><br><span class="line">	<span class="string">"counts"</span> : &#123;</span><br><span class="line">		<span class="string">"input"</span> : <span class="number">9</span>,</span><br><span class="line">		<span class="string">"emit"</span> : <span class="number">9</span>,</span><br><span class="line">		<span class="string">"reduce"</span> : <span class="number">3</span>,</span><br><span class="line">		<span class="string">"output"</span> : <span class="number">3</span></span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意out指定的是一个collection，MapReduce会把结果生产到当前db的out属性指定的集合里。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.length.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">0</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="实例2-求和"><a href="#实例2-求和" class="headerlink" title="实例2-求和"></a>实例2-求和</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.getCollection(<span class="string">'student'</span>).mapReduce(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;emit(<span class="keyword">this</span>.count, <span class="keyword">this</span>.age)&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">key, values</span>)</span>&#123;<span class="keyword">var</span> totalAge = <span class="number">0</span>; <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; values.length; i++)&#123;totalAge += values[i]&#125; <span class="keyword">return</span> totalAge;&#125;, &#123;<span class="attr">out</span>:<span class="string">"totalAge"</span>&#125;);</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"result"</span> : <span class="string">"totalAge"</span>,</span><br><span class="line">	<span class="string">"timeMillis"</span> : <span class="number">53</span>,</span><br><span class="line">	<span class="string">"counts"</span> : &#123;</span><br><span class="line">		<span class="string">"input"</span> : <span class="number">9</span>,</span><br><span class="line">		<span class="string">"emit"</span> : <span class="number">9</span>,</span><br><span class="line">		<span class="string">"reduce"</span> : <span class="number">3</span>,</span><br><span class="line">		<span class="string">"output"</span> : <span class="number">3</span></span><br><span class="line">	&#125;,</span><br><span class="line">	<span class="string">"ok"</span> : <span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">&gt; db.totalAge.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">0</span>, <span class="string">"value"</span> : <span class="number">18</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"value"</span> : <span class="number">12</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"value"</span> : <span class="number">15</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="实例3-求最大值"><a href="#实例3-求最大值" class="headerlink" title="实例3-求最大值"></a>实例3-求最大值</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> maxFun = <span class="function"><span class="keyword">function</span>(<span class="params">key, values</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> maxAge = <span class="number">0</span>; </span><br><span class="line">    values.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">current</span>) </span>&#123;</span><br><span class="line">       <span class="keyword">if</span>(current&gt;maxAge)&#123;</span><br><span class="line">           maxAge = current;</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">return</span> maxAge;</span><br><span class="line">   &#125;;</span><br><span class="line"></span><br><span class="line">db.getCollection(<span class="string">'student'</span>).mapReduce(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;emit(<span class="keyword">this</span>.count, <span class="keyword">this</span>.age)&#125;, maxFun, &#123;<span class="attr">out</span>:<span class="string">"maxAge"</span>&#125;);</span><br><span class="line"></span><br><span class="line">&gt; db.getCollection(<span class="string">'maxAge'</span>).find(&#123;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">0</span>, <span class="string">"value"</span> : <span class="number">9</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"value"</span> : <span class="number">7</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"value"</span> : <span class="number">8</span> &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
<h3 id="实例4-求平均数"><a href="#实例4-求平均数" class="headerlink" title="实例4-求平均数"></a>实例4-求平均数</h3><p>求平均数也很简单，就是把和除以长度。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">var</span> avgFun = <span class="function"><span class="keyword">function</span>(<span class="params">key, values</span>)</span>&#123;<span class="keyword">var</span> totalAge = <span class="number">0</span>; <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; values.length; i++)&#123;totalAge += values[i]&#125; <span class="keyword">return</span> totalAge / values.length;&#125;;</span><br><span class="line">&gt; db.getCollection(<span class="string">'student'</span>).mapReduce(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;emit(<span class="keyword">this</span>.count, <span class="keyword">this</span>.age)&#125;, avgFun, &#123;<span class="attr">out</span>:<span class="string">"avgAge"</span>&#125;);</span><br><span class="line">&gt; db.avgAge.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">0</span>, <span class="string">"value"</span> : <span class="number">6</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"value"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"value"</span> : <span class="number">5</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="实例5-标签统计"><a href="#实例5-标签统计" class="headerlink" title="实例5-标签统计"></a>实例5-标签统计</h3><p>数据准备：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">db.getCollection(<span class="string">'article'</span>).insert(&#123;<span class="attr">name</span>:<span class="string">"article1"</span>, <span class="attr">tags</span>:[<span class="string">'java'</span>,<span class="string">'python'</span>,<span class="string">'mongodb'</span>,<span class="string">'ruby'</span>]&#125;);</span><br><span class="line">db.getCollection(<span class="string">'article'</span>).insert(&#123;<span class="attr">name</span>:<span class="string">"article2"</span>, <span class="attr">tags</span>:[<span class="string">'perl'</span>,<span class="string">'scala'</span>,<span class="string">'mongodb'</span>,<span class="string">'ruby'</span>]&#125;);</span><br><span class="line">db.getCollection(<span class="string">'article'</span>).insert(&#123;<span class="attr">name</span>:<span class="string">"article3"</span>, <span class="attr">tags</span>:[<span class="string">'perl'</span>,<span class="string">'kotlin'</span>,<span class="string">'mongodb'</span>,<span class="string">'ruby'</span>]&#125;);</span><br><span class="line">db.getCollection(<span class="string">'article'</span>).insert(&#123;<span class="attr">name</span>:<span class="string">"article4"</span>, <span class="attr">tags</span>:[<span class="string">'perl'</span>,<span class="string">'kotlin'</span>,<span class="string">'mongodb'</span>,<span class="string">'groovy'</span>]&#125;);</span><br><span class="line">db.getCollection(<span class="string">'article'</span>).insert(&#123;<span class="attr">name</span>:<span class="string">"article5"</span>, <span class="attr">tags</span>:[<span class="string">'perl'</span>,<span class="string">'kotlin'</span>,<span class="string">'redis'</span>,<span class="string">'groovy'</span>]&#125;);</span><br></pre></td></tr></table></figure>
<p>每个文章都有标签，现在要统计每一个标签出现的次数。</p>
<p>有思路吗？这个用mongodb来做实在是太方便了，如果是传统的sql，可能还要好好想想，我们在map的时候，就用每一个tag分组，得到我们要的数据。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">db.article.mapReduce(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; </span><br><span class="line">    <span class="keyword">this</span>.tags.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">currrnt</span>)</span>&#123;</span><br><span class="line">                emit(currrnt, <span class="number">1</span>)</span><br><span class="line">        &#125;);</span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">key, values</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> values.length;</span><br><span class="line">    &#125;, &#123;<span class="attr">out</span>:<span class="string">"aa"</span>&#125;);</span><br><span class="line">&gt; db.aa.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"groovy"</span>, <span class="string">"value"</span> : <span class="number">2</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"java"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"kotlin"</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"value"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"perl"</span>, <span class="string">"value"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"python"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"redis"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"ruby"</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"scala"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="finalize使用"><a href="#finalize使用" class="headerlink" title="finalize使用"></a>finalize使用</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">db.article.mapReduce(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; </span><br><span class="line">    <span class="keyword">this</span>.tags.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">currrnt</span>)</span>&#123;</span><br><span class="line">                emit(currrnt, <span class="number">1</span>)</span><br><span class="line">        &#125;);</span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">key, values</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> values.length;</span><br><span class="line">    &#125;, &#123;<span class="attr">out</span>:<span class="string">"aa"</span>&#125;);</span><br><span class="line">&gt; db.getCollection(<span class="string">'aa'</span>).find(&#123;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"groovy"</span>, <span class="string">"value"</span> : <span class="number">2</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"java"</span>, <span class="string">"value"</span> : &#123; <span class="string">"count"</span> : <span class="number">1</span> &#125; &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"kotlin"</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"value"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"perl"</span>, <span class="string">"value"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"python"</span>, <span class="string">"value"</span> : &#123; <span class="string">"count"</span> : <span class="number">1</span> &#125; &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"redis"</span>, <span class="string">"value"</span> : &#123; <span class="string">"count"</span> : <span class="number">1</span> &#125; &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"ruby"</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"scala"</span>, <span class="string">"value"</span> : &#123; <span class="string">"count"</span> : <span class="number">1</span> &#125; &#125;</span><br><span class="line"><span class="string">``</span><span class="string">`    </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">为什么会出现这样的结果？有的是对象，有的是值，之前说过，如果map产出的values的结果只有一个，是不会执行reduce阶段的，这里可以用finalize来保证结果的统一。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">`</span><span class="string">``</span>js</span><br><span class="line"></span><br><span class="line">db.article.mapReduce(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; </span><br><span class="line">    <span class="keyword">this</span>.tags.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">currrnt</span>)</span>&#123;</span><br><span class="line">                emit(currrnt, &#123;<span class="attr">count</span>:<span class="number">1</span>&#125;)</span><br><span class="line">        &#125;);</span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">key, values</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> values.length;</span><br><span class="line">    &#125;, &#123;<span class="attr">out</span>:<span class="string">"aa"</span>,<span class="attr">finalize</span>: <span class="function"><span class="keyword">function</span>(<span class="params">key,reduced</span>)</span>&#123;</span><br><span class="line">            <span class="keyword">if</span>(reduced.count) &#123;</span><br><span class="line">                <span class="keyword">return</span> reduced.count;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> reduced;</span><br><span class="line">        &#125;&#125;);</span><br><span class="line">&gt; db.getCollection(<span class="string">'aa'</span>).find(&#123;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"groovy"</span>, <span class="string">"value"</span> : <span class="number">2</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"java"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"kotlin"</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"value"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"perl"</span>, <span class="string">"value"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"python"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"redis"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"ruby"</span>, <span class="string">"value"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"scala"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="进阶，mapReduce过滤"><a href="#进阶，mapReduce过滤" class="headerlink" title="进阶，mapReduce过滤"></a>进阶，mapReduce过滤</h3><p>现在我们只统计发布了java标签的数据，可以用query参数来过滤，也可以用map阶段来用代码过滤。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">db.article.mapReduce(function()&#123; </span><br><span class="line">    var flag = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">for</span>(i in <span class="keyword">this</span>.tags)&#123;</span><br><span class="line">        <span class="keyword">if</span>(<span class="keyword">this</span>.tags[i] == <span class="string">'java'</span>) &#123;</span><br><span class="line">            flag = <span class="keyword">true</span>;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(flag) &#123;</span><br><span class="line">        <span class="keyword">this</span>.tags.forEach(function(tag)&#123;</span><br><span class="line">            emit(tag, &#123;count:<span class="number">1</span>&#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;, function(key, values)&#123;</span><br><span class="line">        <span class="keyword">return</span> values.length;</span><br><span class="line">    &#125;, &#123;out:<span class="string">"aa"</span>,finalize: function(key,reduced)&#123;</span><br><span class="line">            <span class="keyword">if</span>(reduced.count) &#123;</span><br><span class="line">                <span class="keyword">return</span> reduced.count;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> reduced;</span><br><span class="line">        &#125;&#125;);</span><br><span class="line">&gt; db.getCollection(<span class="string">'aa'</span>).find(&#123;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"java"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"python"</span>, <span class="string">"value"</span> : <span class="number">1</span> &#125;</span><br></pre></td></tr></table></figure>
<h2 id="聚合框架（aggregation-framework）"><a href="#聚合框架（aggregation-framework）" class="headerlink" title="聚合框架（aggregation framework）"></a>聚合框架（aggregation framework）</h2><p>聚合框架是mongo聚合操作的第三种方式，它与group()解决的问题是的一样的，group()和MapReduce都是需要写函数的，所以mongodb提供了聚合框架，简化聚合操作。</p>
<p>注意：只有MapReduce和聚合框架能分片的环境下使用。</p>
<p>聚合框架是不能自定义函数的，它帮我们实现了一些函数。</p>
<p><a href="https://docs.mongodb.com/manual/core/aggregation-pipeline/index.html" target="_blank" rel="noopener">https://docs.mongodb.com/manual/core/aggregation-pipeline/index.html</a></p>
<p><img src="https://docs.mongodb.com/manual/_images/aggregation-pipeline.bakedsvg.svg" alt=""></p>
<p>聚合框架为我们提供了很多操作，aggregate参数是一个pipeline，每一个按操作按顺序执行。</p>
<p><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/" target="_blank" rel="noopener">https://docs.mongodb.com/manual/reference/operator/aggregation/</a></p>
<p>常用的几个操作：</p>
<ul>
<li>$project 过滤需要用到的字段</li>
<li>$match 查询，过滤需要用到的数据</li>
<li><p>$unwind 用于将一个文档拆成多个文档</p>
<p>  {id:tags[‘java’,’python’,’ruby’]}<br>  $unwind<br>  {id:1,tags:’java’},{id:1,tags:’python’},{id:1,tags:’ruby’}</p>
</li>
<li><p>$group 分组，需要指定<code>_id</code>字段为分组的key</p>
<p>  $group本身又提供一些操作：<a href="https://docs.mongodb.com/manual/reference/operator/aggregation/group/#accumulator-operator" target="_blank" rel="noopener">https://docs.mongodb.com/manual/reference/operator/aggregation/group/#accumulator-operator</a></p>
</li>
</ul>
<h3 id="实例1-长度"><a href="#实例1-长度" class="headerlink" title="实例1-长度"></a>实例1-长度</h3><p>数据准备：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">db.commodity.insert(&#123;<span class="attr">category</span>:<span class="number">1</span>, <span class="attr">price</span>:<span class="number">200</span>, <span class="attr">name</span>: <span class="string">'name1'</span>&#125;);</span><br><span class="line">db.commodity.insert(&#123;<span class="attr">category</span>:<span class="number">1</span>, <span class="attr">price</span>:<span class="number">300</span>, <span class="attr">name</span>: <span class="string">'name2'</span>&#125;);</span><br><span class="line">db.commodity.insert(&#123;<span class="attr">category</span>:<span class="number">2</span>, <span class="attr">price</span>:<span class="number">100</span>, <span class="attr">name</span>: <span class="string">'name3'</span>&#125;);</span><br><span class="line">db.commodity.insert(&#123;<span class="attr">category</span>:<span class="number">2</span>, <span class="attr">price</span>:<span class="number">500</span>, <span class="attr">name</span>: <span class="string">'name4'</span>&#125;);</span><br><span class="line">db.commodity.insert(&#123;<span class="attr">category</span>:<span class="number">3</span>, <span class="attr">price</span>:<span class="number">200</span>, <span class="attr">name</span>: <span class="string">'name5'</span>&#125;);</span><br></pre></td></tr></table></figure>
<p>按照category分组并统计每一组的长度</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.commodity.aggregate(&#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$category'</span>, <span class="attr">totalCount</span>: &#123;<span class="attr">$sum</span>:<span class="number">1</span>&#125;&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">3</span>, <span class="string">"totalCount"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"totalCount"</span> : <span class="number">2</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"totalCount"</span> : <span class="number">2</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="实例2-求和-1"><a href="#实例2-求和-1" class="headerlink" title="实例2-求和"></a>实例2-求和</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.commodity.aggregate(&#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$category'</span>, <span class="attr">totalCount</span>: &#123;<span class="attr">$sum</span>:<span class="number">1</span>&#125;, <span class="attr">totalPrice</span>: &#123;<span class="attr">$sum</span>: <span class="string">'$price'</span>&#125;&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">3</span>, <span class="string">"totalCount"</span> : <span class="number">1</span>, <span class="string">"totalPrice"</span> : <span class="number">200</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"totalCount"</span> : <span class="number">2</span>, <span class="string">"totalPrice"</span> : <span class="number">600</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"totalCount"</span> : <span class="number">2</span>, <span class="string">"totalPrice"</span> : <span class="number">500</span> &#125;</span><br></pre></td></tr></table></figure>
<p>在没有指定排序规则的时候，aggregate是不保证排序的，需要用<code>$sort</code>指定排序。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.commodity.aggregate(&#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$category'</span>, <span class="attr">totalCount</span>: &#123;<span class="attr">$sum</span>:<span class="number">1</span>&#125;, <span class="attr">totalPrice</span>: &#123;<span class="attr">$sum</span>: <span class="string">'$price'</span>&#125;&#125;&#125;, &#123;<span class="attr">$sort</span>: &#123;<span class="string">'totalPrice'</span>:<span class="number">-1</span>&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"totalCount"</span> : <span class="number">2</span>, <span class="string">"totalPrice"</span> : <span class="number">600</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"totalCount"</span> : <span class="number">2</span>, <span class="string">"totalPrice"</span> : <span class="number">500</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">3</span>, <span class="string">"totalCount"</span> : <span class="number">1</span>, <span class="string">"totalPrice"</span> : <span class="number">200</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="实例3-求平均值"><a href="#实例3-求平均值" class="headerlink" title="实例3-求平均值"></a>实例3-求平均值</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.commodity.aggregate(&#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$category'</span>, <span class="attr">totalCount</span>: &#123;<span class="attr">$sum</span>:<span class="number">1</span>&#125;, <span class="attr">totalPrice</span>: &#123;<span class="attr">$sum</span>: <span class="string">'$price'</span>&#125;, <span class="attr">avgPrice</span>: &#123;<span class="attr">$avg</span>:<span class="string">'$price'</span>&#125;&#125;&#125;, &#123;<span class="attr">$sort</span>: &#123;<span class="string">'totalPrice'</span>:<span class="number">-1</span>&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"totalCount"</span> : <span class="number">2</span>, <span class="string">"totalPrice"</span> : <span class="number">600</span>, <span class="string">"avgPrice"</span> : <span class="number">300</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"totalCount"</span> : <span class="number">2</span>, <span class="string">"totalPrice"</span> : <span class="number">500</span>, <span class="string">"avgPrice"</span> : <span class="number">250</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">3</span>, <span class="string">"totalCount"</span> : <span class="number">1</span>, <span class="string">"totalPrice"</span> : <span class="number">200</span>, <span class="string">"avgPrice"</span> : <span class="number">200</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="实例4-标签统计"><a href="#实例4-标签统计" class="headerlink" title="实例4-标签统计"></a>实例4-标签统计</h3><p>之前在演示MapReduce的时候，用MapReduce对article的tags统计tag出现的次数，这里用聚合框架来达到同样的效果，当然想到的就是之前介绍到的<code>$unwind</code>操作。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.aggregate(&#123;<span class="attr">$unwind</span>: <span class="string">'$tags'</span>&#125;, &#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$tags'</span>, <span class="attr">total</span>:&#123;<span class="attr">$sum</span>: <span class="number">1</span>&#125;&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"redis"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"groovy"</span>, <span class="string">"total"</span> : <span class="number">2</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"kotlin"</span>, <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"scala"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"perl"</span>, <span class="string">"total"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"python"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"total"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"java"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"ruby"</span>, <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="实例5-标签过滤"><a href="#实例5-标签过滤" class="headerlink" title="实例5-标签过滤"></a>实例5-标签过滤</h3><p>找出打了java标签的文章并进行统计</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.aggregate(&#123;<span class="attr">$match</span>:&#123;<span class="string">'tags'</span> : &#123;<span class="attr">$in</span>:[<span class="string">'java'</span>]&#125;&#125;&#125;, &#123;<span class="attr">$unwind</span>: <span class="string">'$tags'</span>&#125;, &#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$tags'</span>, <span class="attr">total</span>:&#123;<span class="attr">$sum</span>: <span class="number">1</span>&#125;&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"ruby"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"python"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"java"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="实例6-各种操作"><a href="#实例6-各种操作" class="headerlink" title="实例6-各种操作"></a>实例6-各种操作</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.aggregate(&#123;<span class="attr">$match</span>:&#123;<span class="string">'tags'</span> : &#123;<span class="attr">$nin</span>:[<span class="string">'java'</span>]&#125;&#125;&#125;, &#123;<span class="attr">$unwind</span>: <span class="string">'$tags'</span>&#125;, &#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$tags'</span>, <span class="attr">total</span>:&#123;<span class="attr">$sum</span>: <span class="number">1</span>&#125;&#125;&#125;, &#123;<span class="attr">$sort</span>:&#123;<span class="string">'total'</span>:<span class="number">-1</span>&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"perl"</span>, <span class="string">"total"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"kotlin"</span>, <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"groovy"</span>, <span class="string">"total"</span> : <span class="number">2</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"ruby"</span>, <span class="string">"total"</span> : <span class="number">2</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"redis"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"scala"</span>, <span class="string">"total"</span> : <span class="number">1</span> &#125;</span><br></pre></td></tr></table></figure>
<p>取前三：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.aggregate(&#123;<span class="attr">$match</span>:&#123;<span class="string">'tags'</span> : &#123;<span class="attr">$nin</span>:[<span class="string">'java'</span>]&#125;&#125;&#125;, &#123;<span class="attr">$unwind</span>: <span class="string">'$tags'</span>&#125;, &#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$tags'</span>, <span class="attr">total</span>:&#123;<span class="attr">$sum</span>: <span class="number">1</span>&#125;&#125;&#125;, &#123;<span class="attr">$sort</span>:&#123;<span class="string">'total'</span>:<span class="number">-1</span>&#125;&#125;, &#123;<span class="attr">$limit</span>:<span class="number">3</span>&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"perl"</span>, <span class="string">"total"</span> : <span class="number">4</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"kotlin"</span>, <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br></pre></td></tr></table></figure>
<p>取第二到到第四：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.aggregate(&#123;<span class="attr">$match</span>:&#123;<span class="string">'tags'</span> : &#123;<span class="attr">$nin</span>:[<span class="string">'java'</span>]&#125;&#125;&#125;, &#123;<span class="attr">$unwind</span>: <span class="string">'$tags'</span>&#125;, &#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$tags'</span>, <span class="attr">total</span>:&#123;<span class="attr">$sum</span>: <span class="number">1</span>&#125;&#125;&#125;, &#123;<span class="attr">$sort</span>:&#123;<span class="string">'total'</span>:<span class="number">-1</span>&#125;&#125;,&#123;<span class="attr">$skip</span>:<span class="number">1</span>&#125; ,&#123;<span class="attr">$limit</span>:<span class="number">3</span>&#125;);</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"mongodb"</span>, <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"kotlin"</span>, <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="string">"groovy"</span>, <span class="string">"total"</span> : <span class="number">2</span> &#125;</span><br></pre></td></tr></table></figure>
<p>只显示total：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.aggregate(&#123;<span class="attr">$match</span>:&#123;<span class="string">'tags'</span> : &#123;<span class="attr">$nin</span>:[<span class="string">'java'</span>]&#125;&#125;&#125;, &#123;<span class="attr">$unwind</span>: <span class="string">'$tags'</span>&#125;, &#123;<span class="attr">$group</span>: &#123;<span class="attr">_id</span>:<span class="string">'$tags'</span>, <span class="attr">total</span>:&#123;<span class="attr">$sum</span>: <span class="number">1</span>&#125;&#125;&#125;, &#123;<span class="attr">$sort</span>:&#123;<span class="string">'total'</span>:<span class="number">-1</span>&#125;&#125;,&#123;<span class="attr">$skip</span>:<span class="number">1</span>&#125; ,&#123;<span class="attr">$limit</span>:<span class="number">3</span>&#125;, &#123;<span class="attr">$project</span>:&#123;<span class="attr">_id</span>:<span class="number">0</span>&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"total"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"total"</span> : <span class="number">2</span> &#125;</span><br></pre></td></tr></table></figure>
<p>把total加100</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.article.aggregate(&#123;$match:&#123;<span class="string">'tags'</span> : &#123;$nin:[<span class="string">'java'</span>]&#125;&#125;&#125;, &#123;$unwind: <span class="string">'$tags'</span>&#125;, &#123;$group: &#123;_id:<span class="string">'$tags'</span>, total:&#123;$sum: <span class="number">1</span>&#125;&#125;&#125;, &#123;$sort:&#123;<span class="string">'total'</span>:-<span class="number">1</span>&#125;&#125;,&#123;$skip:<span class="number">1</span>&#125; ,&#123;$limit:<span class="number">3</span>&#125;, &#123;$project:&#123;_id:<span class="number">0</span>,hello:&#123;$add:[<span class="string">'$total'</span>,<span class="number">100</span>]&#125;&#125;&#125;);</span><br><span class="line">&#123; <span class="string">"hello"</span> : <span class="number">103</span> &#125;</span><br><span class="line">&#123; <span class="string">"hello"</span> : <span class="number">103</span> &#125;</span><br><span class="line">&#123; <span class="string">"hello"</span> : <span class="number">102</span> &#125;</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mongo/" rel="tag"># Mongo</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/01/mongo2/" rel="next" title="MongoDB2-查询详解">
                <i class="fa fa-chevron-left"></i> MongoDB2-查询详解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/07/mongo4/" rel="prev" title="MongoDB4-GridFS、Capped Collections、索引与查询计划">
                MongoDB4-GridFS、Capped Collections、索引与查询计划 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#聚合"><span class="nav-number">1.</span> <span class="nav-text">聚合</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#group"><span class="nav-number">1.1.</span> <span class="nav-text">group()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实例-计数"><span class="nav-number">1.1.1.</span> <span class="nav-text">实例-计数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例-最大值"><span class="nav-number">1.1.2.</span> <span class="nav-text">实例-最大值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例-找最小值"><span class="nav-number">1.1.3.</span> <span class="nav-text">实例-找最小值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例4-平均值"><span class="nav-number">1.1.4.</span> <span class="nav-text">实例4-平均值</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#mapReduce"><span class="nav-number">1.2.</span> <span class="nav-text">mapReduce</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实例1-求长度"><span class="nav-number">1.2.1.</span> <span class="nav-text">实例1-求长度</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例2-求和"><span class="nav-number">1.2.2.</span> <span class="nav-text">实例2-求和</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例3-求最大值"><span class="nav-number">1.2.3.</span> <span class="nav-text">实例3-求最大值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例4-求平均数"><span class="nav-number">1.2.4.</span> <span class="nav-text">实例4-求平均数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例5-标签统计"><span class="nav-number">1.2.5.</span> <span class="nav-text">实例5-标签统计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#finalize使用"><span class="nav-number">1.2.6.</span> <span class="nav-text">finalize使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#进阶，mapReduce过滤"><span class="nav-number">1.2.7.</span> <span class="nav-text">进阶，mapReduce过滤</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#聚合框架（aggregation-framework）"><span class="nav-number">1.3.</span> <span class="nav-text">聚合框架（aggregation framework）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#实例1-长度"><span class="nav-number">1.3.1.</span> <span class="nav-text">实例1-长度</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例2-求和-1"><span class="nav-number">1.3.2.</span> <span class="nav-text">实例2-求和</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例3-求平均值"><span class="nav-number">1.3.3.</span> <span class="nav-text">实例3-求平均值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例4-标签统计"><span class="nav-number">1.3.4.</span> <span class="nav-text">实例4-标签统计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例5-标签过滤"><span class="nav-number">1.3.5.</span> <span class="nav-text">实例5-标签过滤</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例6-各种操作"><span class="nav-number">1.3.6.</span> <span class="nav-text">实例6-各种操作</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
